package top.eggcode.modules.user.control;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.eggcode.common.mvc.Result;
import top.eggcode.common.mvc.ResultWrapper;
import top.eggcode.component.query.model.PageList;
import top.eggcode.modules.user.model.*;
import top.eggcode.modules.user.service.RolePowerService;
import top.eggcode.modules.user.service.RoleService;
import top.eggcode.base.BaseController;

import java.util.LinkedList;
import java.util.List;

/**
 * Title: 角色访问接口
 * Description: TODO
 * Date: 2021/5/15 19:57
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Api(tags = "系统角色")
@RequiredArgsConstructor
@RequestMapping("/api/role")
@RestController
public class RoleController extends BaseController<RoleDTO, RoleQuery> {

    private final RoleService selfService;

    private final RolePowerService raletionService;

    @GetMapping("/{id}")
    @Override
    public Result<?> get(@PathVariable String id) {
        RoleBiz entity = selfService.getFull(id).get();
        List<String> idList = new LinkedList<>();
        RoleView view = RoleView.build(entity);
        entity.getPowerList()
                .stream()
                .map(PowerEntity::getId)
                .forEach(idList::add);
        view.setPowers(idList);
        return ResultWrapper.successful(view);
    }

    @ApiOperation("列表")
    @GetMapping("/list")
    public Result<?> list() {
        return super.pack(selfService.find(), RoleView::build);
    }

    @Override
    @ApiOperation("列表分页")
    @GetMapping("/list/page")
    public Result<?> listPage(RoleQuery query) {
        PageList<RoleEntity> page = selfService.page(query);

        return super.pack(page, RoleView::build);
    }


    @ApiOperation("删除")
    @DeleteMapping("/{id}/delete")
    @Override
    public Result<?> delete(@PathVariable String id) {
        selfService.deleteById(id);
        return ResultWrapper.successful();
    }

    @ApiOperation("更新")
    @PatchMapping("/update")
    @Override
    public Result<?> update(@RequestBody RoleDTO view) {
        selfService.put(view.convert());
        List<String> powers = view.getPowers();
        // 更新权限
        raletionService.clearPowers(view.getId());
        powers.forEach(powerId -> {
            rolePowerEntity raletion = new rolePowerEntity();
            raletion.setRoleId(view.getId());
            raletion.setPowerId(powerId);
            raletion.init();
            raletionService.put(raletion);
        });

        return ResultWrapper.successful();
    }

    @ApiOperation("新增")
    @PostMapping("/add")
    @Override
    public Result<?> add(@RequestBody RoleDTO view) {
        // 新增
        selfService.put(view.convert());
        return ResultWrapper.successful();
    }
}
